package com.xuecheng.content.model.dto;

import com.xuecheng.content.model.po.TeachplanMedia;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class CourseCategoryTreeDto  implements Serializable {

    private String id;
    private String name;
    private String label;
    private String parentid;
    private Integer isShow;
    private Integer orderby;
    private Integer isLeaf;
    List<CourseCategoryTreeDto> childrenTreeNodes;

    public CourseCategoryTreeDto(Long id, String pname, Long parentid, Integer grade, String mediaType, LocalDateTime startTime, LocalDateTime endTime, String description, String timelength, Integer orderby, Long courseId, Long coursePubId, Integer status, String isPreview, LocalDateTime createDate, LocalDateTime changeDate, TeachplanMedia teachplanMediaNew) {
    }

    public CourseCategoryTreeDto(String id, String name, String label, String parentid, Integer isShow, Integer orderby, Integer isLeaf) {
        this.id = id;
        this.name = name;
        this.label = label;
        this.parentid = parentid;
        this.isShow = isShow;
        this.orderby = orderby;
        this.isLeaf = isLeaf;
        this.childrenTreeNodes=new ArrayList<>();
    }

    public void addChild(CourseCategoryTreeDto child) {
        childrenTreeNodes.add(child);
    }

    public static List<CourseCategoryTreeDto> buildHierarchy(List<CourseCategoryTreeDto> nodeList) {
        Map<String, CourseCategoryTreeDto> nodeMap = new HashMap<>();
        List<CourseCategoryTreeDto> hierarchy = new ArrayList<>();
        for (CourseCategoryTreeDto node : nodeList) {
            nodeMap.put(node.getId(), node);
        }
        for (CourseCategoryTreeDto node : nodeList) {

            //判断是top字段是不是1，如果是，就加入根节点，如果不是就加入子节点
            if (node.getParentid().equals("1")) {
                hierarchy.add(node);
            } else {
                CourseCategoryTreeDto parent = nodeMap.get(node.getParentid());
                if (parent != null) {
                    parent.addChild(node);
                }
            }
        }
        return hierarchy;
    }

}
